package com.heatup.apt.management.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.heatup.apt.common.constants.UserConstants;
import com.heatup.apt.common.dao.SmsLogMapper;
import com.heatup.apt.common.dao.user.UserAccountRechargeMapper;
import com.heatup.apt.common.dao.user.UserInfoMapper;
import com.heatup.apt.common.util.CheckCodeUtil;
import com.heatup.apt.common.util.JsonTools;
import com.heatup.apt.common.util.RequestTools;
import com.heatup.apt.common.util.ResponseTools;
import com.heatup.apt.common.util.SmsUtil;
import com.heatup.apt.common.util.StringUtil;
import com.heatup.apt.management.service.cashcard.CashcardService;
import com.heatup.apt.management.service.custom.UserAccountConsumeService;
import com.heatup.apt.management.service.custom.UserAccountRechargeService;
import com.heatup.apt.management.util.GenerateShortUrlUtil;
import com.heatup.apt.management.util.ManageConfigPropertiesUtil;
import com.heatup.apt.model.CashcardInfo;
import com.heatup.apt.model.SmsLog;
import com.heatup.apt.model.api.ApiResultModel;
import com.heatup.apt.model.management.SysUser;
import com.heatup.apt.model.user.UserAccountRecharge;
import com.heatup.apt.model.user.UserInfo;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * 储值卡模块后台控制类
 * @author: maxxiang
 * @create: 2016-12-16-
 */
@Controller
@RequestMapping(value = "/system/cashcard")
public class CashcardController extends BaseController {

    @Autowired
    CashcardService cashcardService;

    @Autowired
    private SmsLogMapper smsLogMapper;
    
    @Autowired
    private UserAccountRechargeService userAccountRechargeService;
    
    @Autowired
    private UserInfoMapper userInfoMapper;
    
    @Autowired
    private UserAccountConsumeService userAccountConsumeService;
    
    @Autowired
    private UserAccountRechargeMapper userAccountRechargeMapper;

    private static final Logger log = LoggerFactory.getLogger(CashcardController.class);


    /**
     * 储值卡列表页面 分页查询
     * @return
     */
    @RequestMapping(value = "/to_cashcard_list")
    public ModelAndView to_list(CashcardInfo cashcardInfo,HttpServletRequest request){
        ModelAndView modelAndView = new ModelAndView("cashcard/cashcard_list");
        Integer pageNo = RequestTools.RequestInt(request, "pageNo", 1);
        Integer pageSize = RequestTools.RequestInt(request, "pageSize",10);
        Integer cashcardStatus = RequestTools.RequestInt(request, "cashcardStatus",0);
        String id = RequestTools.RequestString(request, "id",null);
        String checkName = RequestTools.RequestString(request, "checkName","all");
        String cashcardName = RequestTools.RequestString(request, "cashcardName",null);
        
        Map<String,Object> paramsMap = new HashMap<>();
        paramsMap.put("pageNo",pageNo);
        paramsMap.put("pageSize",pageSize);
        paramsMap.put("cashcardStatus",cashcardStatus);
        paramsMap.put("id",id);
        paramsMap.put("checkName",checkName);
        paramsMap.put("cashcardName",cashcardName);
        paramsMap = cashcardService.queryCashcardInfoPage(paramsMap);
        request.getSession().setAttribute("cashcardList",paramsMap.get("listAll") );
        modelAndView.addAllObjects(paramsMap);
        return modelAndView;
    }

    /**
     * 储值卡券添加页面2
     * @return
     */
    @RequestMapping(value = "/to_add_step2/{id}")
    public ModelAndView to_cashcard_add_step2(@PathVariable() Integer id){

        ModelAndView modelAndView = new ModelAndView("cashcard/cashcard_add_step2");
        modelAndView.addObject("id", id);
        modelAndView.addObject("checkList", cashcardService.queryAllCashcardCheckList());//校验人列表
        return modelAndView;
    }
 
    /**
     * 下载文件
     * @param request
     * @param response
     * @throws Exception
     */
	@ResponseBody
	@RequestMapping("/download_file")
	public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String fileName = RequestTools.RequestString(request, "fileName","");
		String baseDir= ManageConfigPropertiesUtil.getString("uploadImagDir");
		response.setContentType("multipart/form-data");
		response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
		File file = new File(baseDir + File.separator + fileName);
		FileInputStream fis = null;
		OutputStream ops = null;
		try {
			fis = new FileInputStream(file);
			HSSFWorkbook wb = new HSSFWorkbook(fis);
			ops = response.getOutputStream();
			wb.write(ops);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fis.close();
				ops.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	 /**
     * 储值卡券添加页面1
     * @return
     */
    @RequestMapping(value = "/to_add_step1")
    public ModelAndView to_cashcard_add_step1(@RequestParam(required = false) Integer id){

        ModelAndView modelAndView = new ModelAndView("cashcard/cashcard_add_step1");
        CashcardInfo cashcardInfo = null;
        if (id !=null){
        	cashcardInfo = cashcardService.queryById(id);
        }
        if (cashcardInfo != null) {
            modelAndView.addObject(cashcardInfo);
            modelAndView.addObject(JSON.toJSONString(cashcardInfo));
        }
        return modelAndView;
    }
    
    /**
     * 优惠券保存1
     * @return
     */
    @RequestMapping(value = "/save_cashcard_add_step1")
    @ResponseBody
    public String save_cashcard_add_step1(CashcardInfo info){

        JSONObject resultJson = new JSONObject();
        resultJson.put("success", false);
        if (info != null) {
            try {
                //检查是否存在相同的名称 兑换/使用时间相冲突的储值卡券
                boolean check = cashcardService.checkByName(info);
                if (check) {
                    //有相同的不可保存
                    resultJson.put("msg", "存在名称相同且兑换时间/使用时间冲突的储值卡券,请修改后再试");
                    return resultJson.toJSONString();
                }

                if (info.getCashcardStatus() != null && info.getCashcardStatus() == 2) {
                    //更新不审核
                    resultJson.put("go", "list");
                }
                cashcardService.saveCashcard(info, getUserInfo().getUserName());
                resultJson.put("success", true);
                resultJson.put("id", info.getId());
            } catch (Exception e) {
                log.error("储值卡券保存step1 失败--->" + e.getMessage() + e.toString());
                resultJson.put("msg", "储值卡券保存失败--->" + e.getMessage());
            }
        }
        return resultJson.toJSONString();
    }

   /**
     * 查看用户的充值记录
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/to_recharge_list")
    public ModelAndView to_userAccountRechargeList(HttpServletRequest request, HttpServletResponse response){
    	Integer pageNo = RequestTools.RequestInt(request, "pageNo", 1);
    	Integer pageSize = RequestTools.RequestInt(request, "pageSize", 10);
    	Integer userId = RequestTools.RequestInt(request, "userId",0);
    	Integer  rechargeType = RequestTools.RequestInt(request, "rechargeType",0);
    	String payStatus = RequestTools.RequestString(request, "payStatus", null);
    	String createTime = RequestTools.RequestString(request, "createTime",null);		
    	ModelAndView model = new ModelAndView();
    	Map<String,Object> paramsMap = new HashMap<String,Object>();
    	Map<String,Object> responseMap = new HashMap<String,Object>();
    	responseMap.put("pageNo",pageNo);
    	/*if (pageNo > 0)
            --pageNo;*/
        if (pageSize <=0)
            pageSize = 10;
        if(payStatus != null){
        	model.setViewName("cashcard/cashcard_refund");// 图款页面
        }else{
        	model.setViewName("cashcard/cashcard_recharge_record");
        }
    	paramsMap.put("userId", userId);
    	paramsMap.put("rechargeType", rechargeType);
    	paramsMap.put("createTime", createTime);
    	paramsMap.put("payStatus", payStatus);
    	Page<UserAccountRecharge> userAccountRechargePage = new Page<>(pageNo,pageSize);
    	UserInfo userInfo = userInfoMapper.selectById(userId);
    	if(userInfo.getAccountAmt().compareTo(BigDecimal.ZERO) == 0 && !StringUtil.isEmpty(payStatus)){
    		return model;
    	}
    	userAccountRechargePage = userAccountRechargeService.queryUserAccountConsumePage(userAccountRechargePage, paramsMap);
    	responseMap.put("list",userAccountRechargePage.getRecords());
    	responseMap.put("userName",userInfo.getNickName());
    	responseMap.put("NO",userInfo.getId());
    	responseMap.put("userId",userId);
    	responseMap.put("userAccount",userInfo.getAccountAmt());
    	responseMap.put("pageAccount",userAccountRechargePage.getTotal());
    	responseMap.put("rechargeType",rechargeType);
    	responseMap.put("createTime",createTime);
    	responseMap.put("sys_userInfo",this.getUserInfo());
    	responseMap.put("userInfo",userInfo);
    	responseMap.put("userAmount",userAccountRechargeMapper.getRechargeAmountByUserId(userId, rechargeType, createTime,payStatus));
    	Map<String,Object> maps = userAccountRechargeService.calculationRdfundAmt(responseMap);
    	responseMap.put("refunAmt",maps.get("refunAmt"));
    	responseMap.remove("userInfo");
    	model.addAllObjects(responseMap);
    	
    	return model;
    }
    
    /**
     * 查看C端用户储值卡消费记录
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/to_consume_list")
    public ModelAndView to_consume_list(HttpServletRequest request, HttpServletResponse response){
    	ModelAndView model = new ModelAndView();
    	Map<String,Object> paramsMap = new HashMap<String,Object>();
    	Map<String,Object> responseMap = new HashMap<String,Object>();
    	Integer pageNo = RequestTools.RequestInt(request, "pageNo", 1);
    	Integer pageSize = RequestTools.RequestInt(request, "pageSize", 10);
    	Integer userId = RequestTools.RequestInt(request, "userId",0);
    	Integer orderType = RequestTools.RequestInt(request, "orderType",1);
    	Integer orderId = RequestTools.RequestInt(request, "orderId",0);
    	String createTime = RequestTools.RequestString(request, "createTime",null);
    	String type = RequestTools.RequestString(request, "type","1");
    	paramsMap.put("pageNo", pageNo);
    	paramsMap.put("pageSize", pageSize);
    	paramsMap.put("userId", userId);
    	paramsMap.put("orderType",orderType);
    	paramsMap.put("orderId",orderId);
    	paramsMap.put("createTime",createTime);
    	paramsMap.put("type",type);
    	paramsMap = userAccountConsumeService.queryUserAccountConsumePage(paramsMap);
    	UserInfo userInfo = userInfoMapper.selectById(userId);
    	paramsMap.put("userAccount",userInfo.getAccountAmt());
    	paramsMap.put("userName",userInfo.getNickName());
    	paramsMap.put("userNo",userInfo.getId());
    	model.addAllObjects(paramsMap);
    	model.setViewName("cashcard/cashcard_consume_record");
    	return model;

    }
    
    /**
     * 发送验证码
     *
     * @param mobile 手机号
     * @return
     */
    @RequestMapping(value = "/send")
    @ResponseBody
    private String send(@RequestParam String mobile) {
        Integer userId = getUserInfo().getId();

        //未登陆
        if(userId == null){
            return "用户未登陆";
        }

        try{
            //检查发送间隔
            Object lastSend = this.getSession(SESSION_KEY_CHECK_CODE_LAST_SEND);
            if(lastSend != null){
                long lastSendTime = (long)lastSend;
                long currentTime = System.currentTimeMillis();
                long seconds =  (currentTime - lastSendTime)/1000;
                if(seconds < UserConstants.SEND_CHECK_CODE_INTERVAL){
                    Map<String,Object> map = new HashMap<>();
                    map.put("nextSendSecond", seconds);
                    return "验证码发送太频繁";
                }
            }

            //检查后台管理员发送限额
            int todayMyCount = smsLogMapper.queryManagementSmsCountByMobileAndUserId(mobile, userId);
            if(todayMyCount > UserConstants.CHECK_CODE_MAX_SEND_COUNT){
                return "已超过今天短信限额";
            }

            Map<String,Object> map = new HashMap<>();
            int checkCode = CheckCodeUtil.getCheckCode();
            boolean sendResult = SmsUtil.sendCheckCode(mobile, checkCode + "");

            //发送记录
            SmsLog smsLog = new SmsLog();
            smsLog.setMobile(mobile);
            smsLog.setCheckCode(checkCode + "");
            smsLog.setUserId(userId);
            smsLog.setSendTime(new Date());
            smsLog.setSendResult(sendResult?1:2);
            smsLog.setSendType(1);
            smsLogMapper.insertSelective(smsLog);

            this.setSession(SESSION_KEY_MOBILE, mobile);
            this.setSession(SESSION_KEY_CHECK_CODE, checkCode);
            this.setSession(SESSION_KEY_CHECK_CODE_LAST_SEND, System.currentTimeMillis());
            map.put("nextSendSecond", UserConstants.SEND_CHECK_CODE_INTERVAL);
            return "success";

        }catch(Exception e){
            return "系统错误" + e.getMessage();
        }
    }

    /**
     * 校验验证码
     *
     * @param checkCode 验证码
     * @param id 优惠券ID
     * @return
     */
    @RequestMapping(value = "/check")
    @ResponseBody
    private String checkCheckCode(@RequestParam String checkCode,
                                  @RequestParam Integer id,
                                  @RequestParam String checkName,
                                  @RequestParam String mobile) {

        Integer userId = getUserInfo().getId();

        //未登陆
        if(userId == null){
            return "未登陆";
        }

        try{
            //有效期验证
            Object syscode = this.getSession(SESSION_KEY_CHECK_CODE);
            Object lastSend = this.getSession(SESSION_KEY_CHECK_CODE_LAST_SEND);
            if(syscode==null || lastSend==null){

                return "无验证码";
            }

            long lastSendTime = (long)lastSend;
            long currentTime = System.currentTimeMillis();
            long seconds =  (currentTime - lastSendTime)/1000;
            if(seconds > UserConstants.CHECK_CODE_TIMEOUT){
                return "验证码已失效,请重新发送";
            }

            //验证码验证
            if(syscode!=null && syscode.toString().equals(checkCode)){
                //验证成功 更新优惠为上线
                cashcardService.updateCashcardToOnline(id, checkName, mobile);
                return "success";

            }else{
                return "验证码错误";
            }
        }catch(Exception e){
            return "系统错误" + e.getMessage();
        }

    }
    
    /**
     * 储值卡导出
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("/download_cashcard")
    public String download_cashcard(HttpServletRequest request,HttpServletResponse response){
    	List<CashcardInfo> list = (List<CashcardInfo>) request.getSession().getAttribute("cashcardList");
    	String msg = cashcardService.downloadCashCard(list);
    	JSONObject jsonObject = new JSONObject();
		Map<String, Object> map = new HashMap<>();
		map.put("fileName",msg);
		map.put("result", "success");
		jsonObject.put("data", map);
		return jsonObject.toJSONString();
    }
    
    /**
     * 储值卡详情分页查询
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("to_cashcard_detail_view")
    public ModelAndView to_cashcard_detail(HttpServletRequest request,HttpServletResponse response){
    	ModelAndView model = new ModelAndView();
    	model.setViewName("cashcard/cashcard_detail_list");
    	Integer cashcard_id = RequestTools.RequestInt(request, "cashcard_id",0);
    	Integer userId = RequestTools.RequestInt(request, "userId",0);
    	Integer pageNo = RequestTools.RequestInt(request, "pageNo",1);
    	String makeTime = RequestTools.RequestString(request, "makeTime",null);
    	Map<String,Object> map = new HashMap<>();
    	map.put("cashcard_id",cashcard_id);
    	if(userId == 0){
    		map.put("userId",null);
    	}else{
    		map.put("userId",userId);
    	}
    	map.put("makeTime", makeTime);
    	map.put("pageNo", pageNo);
    	map = cashcardService.quertCashCardDetailByCardId(map);
    	model.addAllObjects(map);
    	return model;
    }
    
    /**
     * 余卡作废 
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("/cashcard_del")
    public String to_cashcard_del(HttpServletRequest request, HttpServletResponse response){
    	ApiResultModel<Object> apiResultModel = new ApiResultModel<Object>();
    	Integer cashCardId = RequestTools.RequestInt(request, "cashCardId",0);
    	String callback = RequestTools.RequestString(request, "callback","");
    	int bool = 0;
    	try {
    		bool = cashcardService.updateCashcardToOffline(cashCardId);
    		apiResultModel.setData(bool);
    		apiResultModel.setLogined(true);
    		apiResultModel.setErrorCode(1);
		} catch (Exception e) {
			apiResultModel.setData(bool);
			apiResultModel.setLogined(true);
			apiResultModel.setErrorCode(-1);
		}
    	return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
    }
    
    @ResponseBody
    @RequestMapping("/download_detail")
    public String to_download_detail(HttpServletRequest request,HttpServletResponse response){
    	Integer cashcardId = RequestTools.RequestInt(request, "cashcardId",0);
    	Map<String, Object> responseMap = new HashMap<>();
    	responseMap = cashcardService.downloadDetail(cashcardId);
    	JSONObject jsonObject = new JSONObject();
		Map<String, Object> map = new HashMap<>();
		jsonObject.put("data", responseMap);
		return jsonObject.toJSONString();
    }
    
	@ResponseBody
	@RequestMapping("/short_url")
	public String shortUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject resultJson = new JSONObject();
		String cardId = RequestTools.RequestString(request, "cardId","");
		String cashcardUrl = ManageConfigPropertiesUtil.getString("cashcard_code_id_url");
		String cashcardUrl_code_url = cashcardUrl.replace("{cardId}", cardId);
		String shor_coupon_url = GenerateShortUrlUtil.generateShortUrl(cashcardUrl_code_url);
		resultJson.put("data", shor_coupon_url);
		return resultJson.toJSONString();
	}
	
	/**
	 * 个人储值卡退款
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/card_refund")
	@ResponseBody
	public String user_card_refund(HttpServletRequest request,HttpServletResponse response){
		ApiResultModel<Object> apiResultModel = new ApiResultModel<Object>();
		String callback = RequestTools.RequestString(request, "callback","");
		String order_number = RequestTools.RequestString(request, "order_number", "");
		String amt = RequestTools.RequestString(request, "amt", "");
		String remark = RequestTools.RequestString(request, "remark", "");
		Integer consume_id = RequestTools.RequestInt(request, "consume_id", 0);
		SysUser user = this.getUserInfo();
		Map<String,Object> paramMap = new HashMap<>();
		if(user.getRoleId() != 2){
			apiResultModel.setErrorCode(apiResultModel.RET_ERROR);
			apiResultModel.setRet(apiResultModel.RET_ERROR);
			apiResultModel.setMsg("您不是超级管理员！");
			return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
		}
		if(consume_id < 1){
			apiResultModel.setErrorCode(apiResultModel.RET_ERROR);
			apiResultModel.setRet(apiResultModel.RET_ERROR);
			apiResultModel.setMsg("参数错误！");
			return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
		}
		paramMap.put("order_number", order_number);
		paramMap.put("amt", amt);
		paramMap.put("consume_id", consume_id);
		paramMap.put("sys_user", user);
		paramMap.put("remark", remark);
		paramMap = userAccountConsumeService.refundToUserAccountConsumeByOrderNumber(paramMap);
		if((boolean)paramMap.get("bool")){
			apiResultModel.setErrorCode(apiResultModel.RET_SUCCESS);
			apiResultModel.setRet(apiResultModel.RET_SUCCESS);
			apiResultModel.setMsg("退款成功！");
		}
		apiResultModel.setData(paramMap);
		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
	}
}
